package com.cup.bddm.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.cup.bddm.api.req.UserVo;
import com.cup.bddm.api.res.ResVo;
import com.cup.bddm.api.service.UserLogService;
import com.cup.bddm.api.service.UserService;
import com.cup.bddm.handler.Token;
import com.cup.bddm.impala.po.User;
import com.cup.bddm.util.CacheUtil;
import com.cup.bddm.util.MD5Util;

import jodd.util.StringUtil;

/**
 * 用户
 */
@Controller
@RequestMapping(value = "/api/user")
public class UserController extends BaseController {
	@Autowired
	private UserService userService;

	@Autowired
	private UserLogService userLogService;

	/**
	 * 登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public ResVo login(@RequestBody UserVo vo) {
		if (StringUtil.isEmpty(vo.getLogin_name())) {
			return the().login_name().is_empty().vo();
		}
		if (StringUtil.isEmpty(vo.getUser_pwd())) {
			return the().user_pwd().is_empty().vo();
		}
		if (StringUtils.isEmpty(vo.getCup_branch_ins_id_cd())) {
			return the().cup_branch_ins_id_cd().is_empty().vo();
		}
		User user = userService.getUser(vo);
		if (user != null && user.getUser_pwd().equals(MD5Util.MD5(vo.getUser_pwd()))) {
			String lastLogin = userLogService.lastLoginTime(vo);
			user.setLastLogin(lastLogin);
			user.setUser_pwd("******");
			user.setToken(CacheUtil.getToken(user));
			user(user);
			return ResVo.data(user);
		} else {
			return the().login_failed().vo();
		}
	}

	/**
	 * 登出
	 */
	@Token
	@RequestMapping(value = "/out")
	@ResponseBody
	public ResVo out() {
		CacheUtil.delToken(user().getToken());
		return ResVo.ok();
	}

	/**
	 * 用户信息
	 */
	@Token
	@RequestMapping(value = "/info")
	@ResponseBody
	public ResVo info() {
		User user = user();
		UserVo vo = new UserVo();
		vo.setCup_branch_ins_id_cd(user.getCup_branch_ins_id_cd());
		vo.setLogin_name(user.getLogin_name());
		String lastLogin = userLogService.lastLoginTime(vo);
		user.setLastLogin(lastLogin);
		return ResVo.data(user);
	}
}
